import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
Vue.use(VueRouter)
let oldPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location, a = () => { }, b = () => { }) {
    oldPush.call(this, location, a, b)
}
const router = new VueRouter({
    mode: 'history',
    routes,
    scrollBehavior() {
        // 始终滚动到顶部
        return { x: 0, y: 0 }
    },
})
// 创建白名单
let WriteName = [
    "login",
    "home",
    "register",
    "search",
    "detail",
    "addCartSuccess",]
router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token
    let userInfo = store.state.user.userInfo
    if (token) {
        if (to.name === 'login') return next('/home')
        // 获取用户信息,作为凭证需要在请求头中携带token,供后端进行鉴权

        if (Object.keys(userInfo).length <= 0) {
            // 没有就创建,有就直接下一步
            try {
                await store.dispatch('user/userInfoGet')
                next()
            } catch (error) {
                store.dispatch('user/userLogout')
                // 过期就跳转到登录页
                next('/login')
                // alert(error)
                // 当token过期时,携带过期token会导致未登录,所以需要直接清除过期token
            }
        } else {
            next()
        }
    } else if (WriteName.includes(to.name)) {
        next()
    } else {
        next('/login')
    }


})
export default router